<?php
session_start();
if (!file_exists('../install.lock')) {
    header('Location: ../install.php');
    exit;
}

require_once 'config.php';

// 订单超时时间（秒）
$order_timeout = 300;
$now = date('Y-m-d H:i:s');
// 批量更新超时未支付订单为已过期
$update_sql = "UPDATE orders SET status = 'expired' WHERE status = 'pending' AND TIMESTAMPDIFF(SECOND, created_at, ?) > ?";
$stmt = $pdo->prepare($update_sql);
$stmt->execute([$now, $order_timeout]);

$settings = getSettings();
$orders = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $query_key = trim($_POST['query_key'] ?? '');
    $orders = [];
    if (!empty($query_key)) {
        // 先按订单号精确查
        $stmt = $pdo->prepare("SELECT o.*, p.name as product_name, p.duration_type, p.duration_value FROM orders o LEFT JOIN products p ON o.product_id = p.id WHERE o.order_no = ? ORDER BY o.created_at DESC LIMIT 50");
        $stmt->execute([$query_key]);
        $orders = $stmt->fetchAll();
        if (empty($orders)) {
            // 查不到再按取卡密码查
            $card_password_hash = md5($query_key);
            $stmt = $pdo->prepare("SELECT o.*, p.name as product_name, p.duration_type, p.duration_value FROM orders o LEFT JOIN products p ON o.product_id = p.id WHERE o.card_password = ? ORDER BY o.created_at DESC LIMIT 50");
            $stmt->execute([$card_password_hash]);
            $orders = $stmt->fetchAll();
        }
        $_SESSION['orders_result'] = $orders;
        header("Location: orders.php?by=query");
        exit;
    }
} else if (isset($_SESSION['orders_result'])) {
    $orders = $_SESSION['orders_result'];
    unset($_SESSION['orders_result']);
} else {
    // 默认查cookie
    $user_token = $_COOKIE['user_token'] ?? '';
    if (!empty($user_token)) {
        $stmt = $pdo->prepare("SELECT o.*, p.name as product_name, p.duration_type, p.duration_value FROM orders o LEFT JOIN products p ON o.product_id = p.id WHERE o.user_token = ? ORDER BY o.created_at DESC LIMIT 50");
        $stmt->execute([$user_token]);
        $orders = $stmt->fetchAll();
    }
}
?>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <title><?php echo htmlspecialchars($settings['title'] ?? '卡密购买'); ?> - 我的订单</title>
    <link rel="shortcut icon" type="image/x-icon" href="../assets/favicon.ico">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <link rel="stylesheet" type="text/css" href="../assets/css/materialdesignicons.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/animate.min.css">
    <link rel="stylesheet" type="text/css" href="../assets/css/style.min.css">
    <style>
        .order-card {
            transition: transform 0.2s ease;
        }
        .order-card:hover {
            transform: translateY(-2px);
        }
        .status-badge {
            font-size: 12px;
        }
    </style>
</head>

<body>
<!--页面loading-->
<div id="lyear-preloader" class="loading">
    <div class="ctn-preloader">
        <div class="round_spinner">
            <div class="spinner"></div>
            <img src="../assets/images/loading-logo.png" alt="">
        </div>
    </div>
</div>
<!--页面loading end-->

<div class="lyear-layout-web">
    <div class="lyear-layout-container">
        <!-- 导航栏 -->
        <nav class="navbar navbar-expand-lg navbar-light bg-white border-bottom w-100" style="margin:0;padding:0;">
            <div class="container-fluid px-4">
                <a class="navbar-brand" href="index.php">
                    <?php echo htmlspecialchars($settings['title'] ?? '卡密购买'); ?>
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                            <a class="nav-link" href="/">返回首页</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="index.php">购买商品</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="orders.php">我的订单</a>
                        </li>
                    </ul>
                </div>
            </div>
        </nav>
        
        <!--页面主要内容-->
        <main class="lyear-layout-content">
            <div class="container p-t-15">
                <div class="row">
                    <div class="col-12">
                        <div class="page-title-box">
                            <h4 class="page-title">
                                <i class="mdi mdi-format-list-bulleted"></i> 我的订单
                            </h4>
                        </div>
                    </div>
                </div>
                <form method="post" class="mb-4" style="max-width:400px;margin:0 auto;">
                    <div class="input-group">
                        <input type="text" class="form-control" name="query_key" placeholder="请输入订单号或取卡密码" required>
                        <button class="btn btn-primary" type="submit">查询订单</button>
                    </div>
                </form>
                <div class="row justify-content-center">
                    <?php if (empty($orders)): ?>
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body text-center">
                                    <i class="mdi mdi-receipt mdi-48px text-muted"></i>
                                    <h4 class="mt-3">暂无订单</h4>
                                    <p class="text-muted">您还没有任何订单记录</p>
                                    <a href="index.php" class="btn btn-primary">
                                        <i class="mdi mdi-cart-plus"></i> 立即购买
                                    </a>
                                </div>
                            </div>
                        </div>
                    <?php else: ?>
                        <?php foreach ($orders as $order): ?>
                            <div class="col-lg-6 col-xl-4 mb-4 mx-auto">
                                <div class="card order-card h-100">
                                    <div class="card-header">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h6 class="mb-0">
                                                <i class="mdi mdi-receipt"></i> 订单详情
                                            </h6>
                                            <?php
                                            $status_class = '';
                                            $status_text = '';
                                            switch ($order['status']) {
                                                case 'pending':
                                                    $status_class = 'bg-warning';
                                                    $status_text = '待支付';
                                                    break;
                                                case 'paid':
                                                    $status_class = 'bg-success';
                                                    $status_text = '已支付';
                                                    break;
                                                case 'expired':
                                                    $status_class = 'bg-danger';
                                                    $status_text = '已过期';
                                                    break;
                                                default:
                                                    $status_class = 'bg-secondary';
                                                    $status_text = '未知';
                                            }
                                            ?>
                                            <span class="badge <?php echo $status_class; ?> status-badge"><?php echo $status_text; ?></span>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <div class="row mb-2">
                                            <div class="col-6">
                                                <small class="text-muted">订单号</small>
                                                <p class="mb-0 font-weight-bold"><?php echo htmlspecialchars($order['order_no']); ?></p>
                                            </div>
                                            <div class="col-6">
                                                <small class="text-muted">商品名称</small>
                                                <p class="mb-0"><?php
                                                // 商品名称+类型卡(时长)
                                                $type_map = [
                                                    'minute' => '分钟',
                                                    'hour' => '小时',
                                                    'day' => '天',
                                                    'week' => '周',
                                                    'month' => '月',
                                                    'season' => '季',
                                                    'quarter' => '季',
                                                    'year' => '年',
                                                    'forever' => '永久',
                                                    '分钟' => '分钟',
                                                    '小时' => '小时',
                                                    '天' => '天',
                                                    '周' => '周',
                                                    '月' => '月',
                                                    '季' => '季',
                                                    '年' => '年',
                                                    '永久' => '永久'
                                                ];
                                                $type = $type_map[$order['duration_type']] ?? $order['duration_type'];
                                                if ($order['duration_type'] === 'forever' || $order['duration_type'] === '永久') {
                                                    echo htmlspecialchars($order['product_name']) . '';
                                                } else if (!empty($order['duration_value']) && !empty($type)) {
                                                    echo htmlspecialchars($order['product_name']) .'(' . $order['duration_value'] . $type . ')';
                                                } else {
                                                    echo htmlspecialchars($order['product_name']);
                                                }
                                                ?></p>
                                            </div>
                                        </div>
                                        <div class="row mb-2">
                                            <div class="col-6">
                                                <small class="text-muted">购买数量</small>
                                                <p class="mb-0"><?php echo $order['quantity']; ?> 张</p>
                                            </div>
                                            <div class="col-6">
                                                <small class="text-muted">订单金额</small>
                                                <p class="mb-0 text-danger font-weight-bold">￥<?php echo number_format($order['total_amount'], 2); ?></p>
                                            </div>
                                        </div>
                                        <div class="row mb-3">
                                            <div class="col-12">
                                                <small class="text-muted">创建时间</small>
                                                <p class="mb-0"><?php echo date('Y-m-d H:i:s', strtotime($order['created_at'])); ?></p>
                                            </div>
                                        </div>
                                        
                                        <?php if ($order['status'] === 'paid' && !empty($order['paid_at'])): ?>
                                            <div class="row mb-3">
                                                <div class="col-12">
                                                    <small class="text-muted">支付时间</small>
                                                    <p class="mb-0 text-success"><?php echo date('Y-m-d H:i:s', strtotime($order['paid_at'])); ?></p>
                                                </div>
                                            </div>
                                        <?php endif; ?>
                                        
                                        <!-- 操作按钮 -->
                                        <div class="d-grid gap-2">
                                            <?php if ($order['status'] === 'pending'): ?>
                                                <a href="payment.php?order_no=<?php echo $order['order_no']; ?>" class="btn btn-primary btn-sm">
                                                    <i class="mdi mdi-credit-card"></i> 继续支付
                                                </a>
                                            <?php elseif ($order['status'] === 'paid'): ?>
                                                <a href="success.php?order_no=<?php echo $order['order_no']; ?>" class="btn btn-success btn-sm">
                                                    <i class="mdi mdi-eye"></i> 查看卡密
                                                </a>
                                            <?php elseif ($order['status'] === 'expired'): ?>
                                                <a href="failed.php?order_no=<?php echo $order['order_no']; ?>" class="btn btn-warning btn-sm">
                                                    <i class="mdi mdi-information"></i> 查看详情
                                                </a>
                                            <?php endif; ?>
                                            
                                            <button type="button" class="btn btn-outline-secondary btn-sm" onclick="copyOrderNo('<?php echo $order['order_no']; ?>')">
                                                <i class="mdi mdi-content-copy"></i> 复制订单号
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                
                <!-- 订单统计 -->
                <?php if (!empty($orders)): ?>
                    <div class="row mt-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5><i class="mdi mdi-chart-bar"></i> 订单统计</h5>
                                </div>
                                <div class="card-body">
                                    <div class="row text-center">
                                        <?php
                                        $total_orders = count($orders);
                                        $paid_orders = count(array_filter($orders, function($o) { return $o['status'] === 'paid'; }));
                                        $pending_orders = count(array_filter($orders, function($o) { return $o['status'] === 'pending'; }));
                                        $expired_orders = count(array_filter($orders, function($o) { return $o['status'] === 'expired'; }));
                                        $total_amount = array_sum(array_column(array_filter($orders, function($o) { return $o['status'] === 'paid'; }), 'total_amount'));
                                        ?>
                                        <div class="col-md-3 mb-3">
                                            <div class="border rounded p-3">
                                                <h4 class="text-primary"><?php echo $total_orders; ?></h4>
                                                <small class="text-muted">总订单数</small>
                                            </div>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <div class="border rounded p-3">
                                                <h4 class="text-success"><?php echo $paid_orders; ?></h4>
                                                <small class="text-muted">已支付</small>
                                            </div>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <div class="border rounded p-3">
                                                <h4 class="text-warning"><?php echo $pending_orders; ?></h4>
                                                <small class="text-muted">待支付</small>
                                            </div>
                                        </div>
                                        <div class="col-md-3 mb-3">
                                            <div class="border rounded p-3">
                                                <h4 class="text-danger">￥<?php echo number_format($total_amount, 2); ?></h4>
                                                <small class="text-muted">总消费</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </main>
    </div>
</div>

<script src="../assets/js/jquery.min.js"></script>
<script src="../assets/js/popper.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/perfect-scrollbar.min.js"></script>
<script src="../assets/js/main.min.js"></script>
<script>
// 复制订单号
function copyOrderNo(orderNo) {
    navigator.clipboard.writeText(orderNo).then(function() {
        alert('订单号已复制到剪贴板');
    }).catch(function(err) {
        alert('复制失败，请手动复制');
    });
}
</script>
</body>
</html> 